package org.jeecg.modules.wechat.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.wechat.utils.HttpClientUtil;
import org.jeecg.modules.wechat.config.WechatConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信订阅消息服务类
 */
@Slf4j
@Service
public class WechatSubscribeService {
    
    @Autowired
    private WechatConfig wechatConfig;

    @Autowired
    private RestTemplate restTemplate;
    
    private String accessToken;
    private long tokenExpireTime;
    
    /**
     * 获取access_token
     */
    public String getAccessToken() {
        if (accessToken != null && System.currentTimeMillis() < tokenExpireTime) {
            return accessToken;
        }
        JSONObject jsonobject;
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}";
        Map<String, String> params = new  HashMap<>();
        params.put("appid", wechatConfig.getAppIdms());
        params.put("secret", wechatConfig.getAppSecretms());

        String result = restTemplate.getForEntity(url, String.class, params).getBody();
        jsonobject = JSON.parseObject(result);
        accessToken = jsonobject.getString("access_token");
        return accessToken;
    }
    
    /**
     * 发送注册成功通知
     */
    public boolean sendRegisterSuccessMessage(String openid, String phoneNumber) {
        String templateId = "Yw0XP5EHM6RhZDvWSNc_FoEL2g4MDM3UCaGWKFjh9KU";
        
        Map<String, TemplateData> data = new HashMap<>();
        data.put("phone_number1", new TemplateData(phoneNumber));
        data.put("phrase2", new TemplateData("通过审核"));
        data.put("thing3", new TemplateData("已通过审核，请尽快签约腾讯电子签"));

        String page = "pages/index/index"; // 跳转页面
        
        return sendSubscribeMessage(openid, templateId, data, page);
    }
    
    /**
     * 发送订阅消息
     */
    public boolean sendSubscribeMessage(String openid, String templateId, 
                                      Map<String, TemplateData> data, String page) {
        try {
            String accessToken = getAccessToken();
            String url = wechatConfig.getSubscribeMessageUrl() + "?access_token=" + accessToken;
            
            SubscribeMessageRequest request = new SubscribeMessageRequest();
            request.setTouser(openid);
            request.setTemplate_id(templateId);
            request.setData(data);
            request.setPage(page);
            
            String requestBody = JSON.toJSONString(request);
            log.info("发送订阅消息请求: {}", requestBody);
            System.out.println("发送订阅消息请求: " + requestBody);
            
            String response = HttpClientUtil.post(url, requestBody);
            JSONObject messageResponse = JSON.parseObject(response);
            
            Integer errcode = messageResponse.getInteger("errcode");
            if (errcode == 0) {
                log.info("订阅消息发送成功, openid: {}", openid);
                System.out.println("订阅消息发送成功, openid: " + openid);
                return true;
            } else {
                log.error("订阅消息发送失败, openid: {}, errcode: {}, errmsg: {}", 
                         openid, errcode, messageResponse.getString("errmsg"));
                System.out.println("订阅消息发送失败, openid: " + openid + ", errcode: " + errcode + ", errmsg: " + messageResponse.getString("errmsg"));
                return false;
            }
            
        } catch (Exception e) {
            log.error("发送订阅消息异常, openid: {}", openid, e);
            System.out.println("发送订阅消息异常, openid: " + openid + ", exception: " + e.getMessage());
            return false;
        }
    }
    
    /**
     * 模板数据类
     */
    public static class TemplateData {
        private String value;
        
        public TemplateData() {}
        
        public TemplateData(String value) {
            this.value = value;
        }
        
        // Getters and Setters
        public String getValue() {
            return value;
        }
        
        public void setValue(String value) {
            this.value = value;
        }
    }
    
    /**
     * 订阅消息请求类
     */
    public static class SubscribeMessageRequest {
        private String touser;
        private String template_id;
        private String page;
        private Map<String, TemplateData> data;
        
        // Getters and Setters
        public String getTouser() {
            return touser;
        }
        
        public void setTouser(String touser) {
            this.touser = touser;
        }
        
        public String getTemplate_id() {
            return template_id;
        }
        
        public void setTemplate_id(String template_id) {
            this.template_id = template_id;
        }
        
        public String getPage() {
            return page;
        }
        
        public void setPage(String page) {
            this.page = page;
        }
        
        public Map<String, TemplateData> getData() {
            return data;
        }
        
        public void setData(Map<String, TemplateData> data) {
            this.data = data;
        }
    }
}